package com.tboss.am.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.tboss.am.dto.AMDto;
import com.tboss.am.dto.CriticalDto;
import com.tboss.am.dto.ResourceCollectorDto;
import com.tboss.am.dto.ServerDto;
import com.tboss.am.service.AMService;
import com.tboss.am.service.CriticalService;
import com.tboss.am.service.ResourceCollectorMaxService;
import com.tboss.am.service.ResourceCollectorService;
import com.tboss.am.service.ServerInfoService;
import com.tboss.am.service.ServerService;

@Controller
@RequestMapping(value = "/am")
public class AMController {
		
	@Autowired private AMService amService;
	@Autowired private ServerInfoService serverInfoService;
	@Autowired private ServerService serverService;
	@Autowired private CriticalService criticalService;
	@Autowired private ResourceCollectorService resourceCollectorService;
	@Autowired private ResourceCollectorMaxService resourceCollectorMaxService;
	
	private boolean flag = true;
	
	// "/am/main"
	// 자산관리 메뉴
	@RequestMapping(value = "/main", method = {RequestMethod.GET, RequestMethod.POST})
	public String home(Model model, HttpServletRequest req, ServerDto serverDto, CriticalDto criticalDto) {
		String rtnUrl = req.getServletPath().substring(1);
		System.out.println(rtnUrl);		
			
		// List<ServerInfoDto> serverInfoList = this.serverInfoService.selectAll();
		List<AMDto> amList = this.amService.selectAll();
		List<ResourceCollectorDto> rscCollectDtoList = this.amService.selectRscList();
		// List<ResourceCollectorDto> rscCollectSvrDtoList = this.amService.selectSvrRscList(svrNum);
		
		/*
		System.out.println("Before: " + serverInfoList.size());
		for(int i = 0; i < serverInfoList.size(); i++){
			System.out.println(serverInfoList.get(i).getVisible());
			// Remove a list when visible == "N"
			if(serverInfoList.get(i).getVisible().equals("N")){
				serverInfoList.remove(i);				
			}
		}
		*/
		System.out.println("Before: " + amList.size());
		for(int i = 0; i < amList.size(); i++){
			System.out.println(amList.get(i).getVisible());
			// Remove a list when visible == "N"
			if(amList.get(i).getVisible().equals("N")){
				amList.remove(i);				
			}
		}
		System.out.println("After: " + amList.size());
		
		model.addAttribute("amList", amList);
		model.addAttribute("rscCollectDtoList", rscCollectDtoList);
		// model.addAttribute("rscCollectSvrDtoList", rscCollectSvrDtoList);
		
		// 받아온 서버 정보가 없으면 Ajax 사용. header 중첩 방지.
		return rtnUrl+"Ajax";
		
		/*
		if(flag == true){			
			return rtnUrl+"Ajax";
		}
		else{
			flag = true;
			return rtnUrl;
		}
		*/
	}

	// "/am/test"
	// Ajax 테스트
	@RequestMapping(value = "/test", method = {RequestMethod.GET, RequestMethod.POST})
	public void getTest(@RequestParam("testStr") String testStr, HttpServletRequest request, Model model, int svrNum) {
		// AMDto amDto = this.amService.selectMaxOne(svrNum);
		
		// model.addAttribute("amDto", amDto);
		
		System.out.println("-------- str:"+testStr+"svrNum:"+ svrNum);		
	}
	
	// "/am/svrReg"
	// 서버등록 메뉴
	@RequestMapping(value = "/svrReg", method = {RequestMethod.GET, RequestMethod.POST})
	public String addSvr(Model model, HttpServletRequest req, ServerDto serverDto, CriticalDto criticalDto) {
						
		String rtnUrl = req.getServletPath().substring(1);
		System.out.println(rtnUrl);
		return rtnUrl+"Ajax";			
	}
	
	// "/am/cancel"
	// 취소버튼 메뉴
	@RequestMapping(value = "/cancel", method = {RequestMethod.GET, RequestMethod.POST})
	public void cancel(Model model, HttpServletRequest req, HttpServletResponse res, ServerDto serverDto, CriticalDto criticalDto) {

		flag = false;
		// insert 이후에 home()으로 바로 redirect.
		try {
			res.sendRedirect("localhost:8080/am/main");
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
	
	// "/am/svrModify"
	// 서버정보 수정 메뉴
	@RequestMapping(value = "/svrModify", method = {RequestMethod.GET, RequestMethod.POST})
	public String svrModify(Model model, HttpServletRequest req, ServerDto serverDto, CriticalDto criticalDto, int svrNum, String serialNo) {
					
		ServerDto serverOne = this.serverService.selectOne(svrNum);
		CriticalDto criticalOne = this.criticalService.selectOne(serialNo);
		
		model.addAttribute("serverOne", serverOne);
		model.addAttribute("criticalOne", criticalOne);
		
		String rtnUrl = req.getServletPath().substring(1);		
		System.out.println(rtnUrl);
		// return rtnUrl+"Ajax";
		return rtnUrl;
			
	}
	
	// "/am/submit"
	// 실질적인 서버 등록을 실행
	@RequestMapping(value = "/submit", method = {RequestMethod.GET, RequestMethod.POST})
	public void submit(Model model, HttpServletRequest req, HttpServletResponse res, ServerDto serverDto, CriticalDto criticalDto){	
		String rtnUrl = req.getServletPath().substring(1);
		System.out.println(rtnUrl);
			
		this.serverService.insert(serverDto);
		this.criticalService.insert(criticalDto);
		// return rtnUrl+"Ajax";
		
		flag = false;
		// insert 이후에 home()으로 바로 redirect.
		
		try {
			res.sendRedirect("localhost:8080/am/main");
		} catch (IOException e) {
			e.printStackTrace();
		}
				
	}
	
	// "/am/update"
	// 실질적인 서버 정보 수정을 실행
	@RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST})
	public void update(Model model, HttpServletRequest req, HttpServletResponse res, ServerDto serverDto, CriticalDto criticalDto){
		
		CriticalDto criDto = criticalDto;
		criDto.setSerialNo(serverDto.getSerialNo());
		this.serverService.update(serverDto);
		this.criticalService.update(criDto);			
	
		String rtnUrl = req.getServletPath().substring(1);
		System.out.println(rtnUrl);
		// return rtnUrl+"Ajax";
		
		flag = false;
		// insert 이후에 home()으로 바로 redirect.
		
		try {
			res.sendRedirect("localhost:8080/am/main");
		} catch (IOException e) {
			e.printStackTrace();
		}
				
	}
	
	// "/am/regTest"
	// Ajax, JSON을 이용한 예외처리
	@RequestMapping(value = "/regTest", method = {RequestMethod.GET, RequestMethod.POST})
	public Model regTest(@RequestParam("host") String host, ServerDto serverDto, CriticalDto criticalDto,
			Model model, HttpServletRequest request, HttpServletResponse response) {
		System.out.println(serverDto.getHost());
		System.out.println(serverDto.getSerialNo());
		
		String hostName = serverDto.getHost();
    	String serialNoName = serverDto.getSerialNo();
    	
    	int cpuCriticalFigure = criticalDto.getCpuCritical();
    	int cpuMajorFigure = criticalDto.getCpuMajor();
    	int cpuMinorFigure = criticalDto.getCpuMinor();

    	int memoryCriticalFigure = criticalDto.getMemoryCritical();
    	int memoryMajorFigure = criticalDto.getMemoryMajor();
    	int memoryMinorFigure = criticalDto.getMemoryMinor();
    	
    	int hddCriticalFigure = criticalDto.getHddCritical();
    	int hddMajorFigure = criticalDto.getHddMajor();
    	int hddMinorFigure = criticalDto.getHddMinor();

    	response.setCharacterEncoding("UTF-8");	
    	response.setContentType("text/xml");
    	
    	List<ServerDto> serverList = this.serverService.selectAll();
    	
    	// 만약 등록된 서버가 없는 경우에는 제한 없이 등록 가능.
    	if(serverList.size() == 0)
    		model.addAttribute("msg","correct");
    	
    	// 등록된 서버가 하나라도 존재할 경우에는 예외처리.
    	System.out.println("serverList's size: " + serverList.size());
		for(int i = 0; i < serverList.size(); i++){
			try{
				// Unique host check.
				if(serverList.get(i).getHost().equals(hostName)){				
					System.out.println("incorrectHost");
					model.addAttribute("hostMsg", "incorrectHost");
				}
				// Unique serialNo check.		
				else if(serverList.get(i).getSerialNo().equals(serialNoName)){
					System.out.println("incorrectSerial");
					model.addAttribute("serialMsg", "incorrectSerial");
				}else if(cpuCriticalFigure <= cpuMajorFigure || cpuCriticalFigure <= cpuMinorFigure || cpuMajorFigure <= cpuMinorFigure){
					model.addAttribute("cpuMsg", "incorrectCpu");
				}
				else if(memoryCriticalFigure <= memoryMajorFigure || memoryCriticalFigure <= memoryMinorFigure || memoryMajorFigure <= memoryMinorFigure){
					model.addAttribute("memoryMsg", "incorrectMemory");
				}
				else if(hddCriticalFigure <= hddMajorFigure || hddCriticalFigure <= hddMinorFigure || hddMajorFigure <= hddMinorFigure){
					model.addAttribute("hddMsg", "incorrectHdd");
				}	
				else{
					model.addAttribute("correctMsg", "correct");
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			
 		}		
				
		return model;
		
	}	
	
	// "/am/rscCollect"
	// 차후 Ajax를 활용하여 수집정보만 selectAll하는 메소드.
	@RequestMapping(value = "/rscCollect", method = {RequestMethod.GET, RequestMethod.POST})
//	public Model rscCollect(@RequestParam("svrNum") int svrNum, ServerDto serverDto, CriticalDto criticalDto, AMDto amDto,
	public Model rscCollect(ServerDto serverDto, CriticalDto criticalDto, AMDto amDto,
			Model model, HttpServletRequest request, HttpServletResponse response, int svrNum) {
		System.out.println("svrNum: " + svrNum);
		
		List<ResourceCollectorDto> rscCollectDtoList = this.amService.selectRscList();
		List<ResourceCollectorDto> rscCollectSvrDtoList = this.amService.selectSvrRscList(svrNum);
		ResourceCollectorDto rscCollectAlarm = this.amService.selectMaxOne(svrNum);
		
		model.addAttribute("rscCollectDtoList", rscCollectDtoList);
		model.addAttribute("rscCollectSvrDtoList", rscCollectSvrDtoList);
		model.addAttribute("rscCollectAlarm", rscCollectAlarm);
		
		for(int i = 0; i < rscCollectSvrDtoList.size(); i++){
			System.out.println(rscCollectSvrDtoList.get(i).getCollectionTime());
		}
		
		System.out.println(rscCollectAlarm.getCollectionTime());
		/*
		for(int i = 0; i < rscCollectDtoList.size(); i++)
			System.out.println(rscCollectDtoList.get(i).getCollectionTime()+" | "+rscCollectDtoList.get(i).getSvrNum()
					+" | "+rscCollectDtoList.get(i).getAlarmCpu()+" | "+rscCollectDtoList.get(i).getAlarmMem()
					+" | "+rscCollectDtoList.get(i).getAlarmHdd());
		*/
		
		return model;
		
	}
}
